const collectDao = require('../dao/collectDao');
const productDao = require('../dao/productDao');
const checkLogin = require('../middleware/checkLogin');

module.exports = {
    addCollect: async ctx => {
        const { user_id, product_id } = ctx.request.body;
        // 判断用户是否登录
        if (!checkLogin(ctx, user_id)) {
            return
        }
        try {
            // 首先判断是否收藏过该商品
            const result = await collectDao.findCollect(user_id, product_id);
            if (result.length) {
                ctx.body = {
                    status: 80200,
                    message: 'success',
                    data: {
                        code: '3',
                        msg: '您已收藏过该商品，请到我的收藏查看'
                    }
                }
                return
            }
            // 获取当前时间
            const timeTemp = Date.now();
            const res = await collectDao.addCollect(user_id, product_id, timeTemp);
            if (res.affectedRows === 1) {
                ctx.body = {
                    status: 80200,
                    message: 'success',
                    data: {
                        code: '1',
                        msg: '添加收藏成功'
                    }
                }
                return;
            }
        } catch (error) {
            return Promise.reject(error)
        }
    },
    getCollect: async ctx => {
        const { user_id } = ctx.request.body;
        // 校验用户是否登录
        if (!checkLogin(ctx, user_id)) {
            return;
        }
        try {
            const collect = await collectDao.getCollect(user_id);
            if (!collect.length) {
                ctx.body = {
                    status: 80200,
                    message: 'success',
                    data: {
                        code: '2',
                        msg: '该用户没有收藏的商品'
                    }
                }
                return;
            }
            const collectList = [];
            for (let i = 0; i < collect.length; i++) {
                const temp = collect[i];
                // 获取每个商品的详细信息
                const product = await productDao.getProductDetailsById(temp.product_id);
                collectList.push(product[0])
            }
            ctx.body = {
                status: 80200,
                message: 'success',
                data: collectList
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }
}